package com.dctp.common.core;

import com.amazonaws.HttpMethod;
import com.amazonaws.auth.AWSStaticCredentialsProvider;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3ClientBuilder;
import com.amazonaws.services.s3.model.GeneratePresignedUrlRequest;
import java.net.URL;
import java.util.Date;

public class S3PresignedUrlGenerator {

    private static final String ACCESS_KEY = "4c7a16cdeaf30d89be0e55732141e515";
    private static final String SECRET_KEY = "44e70cdf7b3338f341d96223106c1aaee2315bd2556367e92d3492802072c253";
    private static final String BUCKET_NAME = "dctp-bucket";
    private static final String R2_ENDPOINT = "https://58d18639a4e80800a7ca71fc87fd082c.r2.cloudflarestorage.com";  // R2 Endpoint

    public static String generatePresignedUrl(String fileName, String fileType) {
        try {
            // 创建 S3 客户端
            AmazonS3 s3Client = AmazonS3ClientBuilder.standard()
                    .withEndpointConfiguration(new AmazonS3ClientBuilder.EndpointConfiguration(R2_ENDPOINT, "auto"))
                    .withCredentials(new AWSStaticCredentialsProvider(new BasicAWSCredentials(ACCESS_KEY, SECRET_KEY)))
                    .build();

            // 设置上传文件的参数
            GeneratePresignedUrlRequest generatePresignedUrlRequest = new GeneratePresignedUrlRequest(BUCKET_NAME, fileName)
                    .withMethod(HttpMethod.PUT)  // 上传文件需要使用 PUT 方法
                    .withExpiration(new Date(System.currentTimeMillis() + 1000 * 60 * 60))  // 设置 URL 有效期，这里设置为 1 小时
                    .withContentType(fileType);  // 设置上传文件的类型

            // 生成预签名 URL
            URL url = s3Client.generatePresignedUrl(generatePresignedUrlRequest);
            return url.toString();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }


    public static void main(String[] args) {
        String fileName = "logo.png";
        String fileType = "image/png";  // 文件类型

        String presignedUrl = generatePresignedUrl(fileName, fileType);
        System.out.println("Generated Presigned URL: " + presignedUrl);
    }
}
